<template>
  <el-button type="primary" @click="openModal">上传</el-button>
  <el-dialog v-model="visible" title="文件上传">
    <div class="upload-container" @dragover.prevent @drop="handleDrop">
      <input type="file" accept=".pdf,.docx,.pptx" @change="handleFileSelect" style="display: none" ref="fileInput">
      <div class="upload-area" @click="openFileDialog">
        <p v-if="selectedFileName">已选择文件：{{selectedFileName}}</p>
        <template v-else>
          <p>点击选择文件</p>
          <p>或拖拽文件到此处</p>
        </template>
      </div>
      <el-progress
          :percentage="uploadProgress"
          v-if="isUploading"
          status="success"
          :stroke-width="20"
          class="custom-progress"
      ></el-progress>
    </div>
    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="startUpload" :disabled="!selectedFile">确认上传</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, defineEmits } from 'vue';
import request from '../utils/request';
import SparkMD5 from 'spark-md5';

const emits = defineEmits(['uploadSuccess'])
const fileInput = ref(null);
const selectedFile = ref(null);
const selectedFileName = ref(null)
const isUploading = ref(false);
const uploadProgress = ref(0);
const visible = ref(false);

const handleFileSelect = (e) => {
  const file = e.target.files[0];
  if (file) {
    selectedFile.value = file;
    selectedFileName.value = file.name;
  }
};

const openFileDialog = () => {
  fileInput.value.click();
};

const handleDrop = (e) => {
  e.preventDefault();
  const file = e.dataTransfer.files[0];
  if (file) {
    selectedFile.value = file;
    selectedFileName.value = file.name;
  }
};

const openModal = () => {
  visible.value = true;
};

const calculateHash = (file, chunkSize) => {
  return new Promise((resolve) => {
    const fileReader = new FileReader();
    const spark = new SparkMD5.ArrayBuffer();
    const totalChunks = Math.ceil(file.size / chunkSize);
    let currentChunk = 0;

    const loadNext = () => {
      const start = currentChunk * chunkSize;
      const end = Math.min(start + chunkSize, file.size);
      fileReader.readAsArrayBuffer(file.slice(start, end));
    };

    fileReader.onload = (e) => {
      spark.append(e.target.result);
      currentChunk++;
      if (currentChunk < totalChunks) {
        loadNext();
      } else {
        resolve(spark.end());
      }
    };

    loadNext();
  });
};

const calculateChunkHash = (chunk) => {
  return new Promise((resolve) => {
    const fileReader = new FileReader();
    const spark = new SparkMD5.ArrayBuffer();
    fileReader.onload = (e) => {
      spark.append(e.target.result);
      resolve(spark.end());
    };
    fileReader.readAsArrayBuffer(chunk);
  });
};

const startUpload = async () => {
  if (!selectedFile.value) return;
  isUploading.value = true;
  // 分片大小
  const chunkSize = 1024 * 1024;
  const file = selectedFile.value;
  const totalChunks = Math.ceil(file.size / chunkSize);
  let uploadedChunks = 0;

  // 计算文件总 hash
  const fileHash = await calculateHash(file, chunkSize);
  console.log('总 fileHash',fileHash)
  for (let i = 0; i < totalChunks; i++) {
    let isUploaded = false;
    while (!isUploaded) {
      const start = i * chunkSize;
      const end = Math.min(start + chunkSize, file.size);
      const chunk = file.slice(start, end);
      const chunkHash = await calculateChunkHash(chunk);
      console.log('分片 chunkHash',chunkHash)
      const formData = new FormData();
      formData.append('file', chunk);
      formData.append('fileName', file.name);
      formData.append('chunkIndex', i);
      formData.append('totalChunks', totalChunks);
      formData.append('fileHash', fileHash);
      formData.append('chunkHash', chunkHash);

      setTimeout(() => {
        isUploaded = true;
        uploadedChunks++;
        uploadProgress.value = (uploadedChunks / totalChunks) * 100;
      },500)

     /* try {
        await request.post('/file/upload', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        });
        isUploaded = true;
        uploadedChunks++;
        uploadProgress.value = (uploadedChunks / totalChunks) * 100;
      } catch (error) {
        console.error(`分片 ${i} 上传失败，重试中...`, error);
      }*/
    }
  }
  console.log('merge',selectedFile.value.name,fileHash,totalChunks,selectedFile.value.size,selectedFile.value.type)
  // 上传完成后提交文件总 hash 给后端进行合并
 /* try {
    await request.post('/file/merge', {
      fileName: selectedFile.value.name,
      fileHash: fileHash,
      totalChunks: totalChunks,
      fileSize: selectedFile.value.size,
      fileType: selectedFile.value.type
    });
  } catch (error) {
    console.error('文件合并失败', error);
  }*/

  isUploading.value = false;
  visible.value = false;
  selectedFileName.value = '';
  emits('uploadSuccess')
};
</script>

<style scoped>
.upload-container {
  text-align: center;
  padding: 20px;
}

.upload-area {
  border: 2px dashed #ccc;
  padding: 40px;
  margin-bottom: 20px;
  cursor: pointer;
  transition: border-color 0.3s;
}

.upload-area:hover {
  border-color: #007bff;
}

.custom-progress .el-progress-bar__inner {
  background-color: #007bff;
}
</style>